package com.itshops.controller;


import com.itshops.entity.User;
import com.itshops.service.UserService;
import com.itshops.service.impl.UserServiceImpl;
import com.itshops.utils.Constants;

import javax.imageio.ImageIO;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Random;

/**
 * 实现用户模块的控制层
 * 包含登录和注册
 * */
@WebServlet("/user")
public class UserController extends BaseServlet {

    UserService userService = new UserServiceImpl();
    //用户注册验证
    public String check(HttpServletRequest req,HttpServletResponse resp) throws SQLException {

        //获取用户名
        String username = req.getParameter("username");
        if (username == null) {
            return "1";//直接不能注册
        }
        //信息验证，用户名是否存在

        boolean b = userService.checkedUser(username);
        //响应数据
        if (b) {
            //用户存在返回1
            return "1";
        }
        //用户不存在返回0
        return "0";
    }

    //用户注册
    public String register(HttpServletRequest req,HttpServletResponse resp){
        //获取用户信息
        User user = new User();
        user.setUsername(req.getParameter("uName"));
        user.setUpassword(req.getParameter("uPassword"));
        user.setUsex(req.getParameter("uSex"));
        user.setEmail(req.getParameter("uEmail"));
        //设置为普通用户
        user.setUrole(0);


        //调用业务逻辑
        try {
            int i = userService.register(user);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            req.setAttribute("registerMsg","注册失败!");
           return Constants.FORWARD+"/register.jsp";
        }
        //响应
        req.setAttribute("usname",user.getUsername());
        return Constants.FORWARD+"registerSuccess.jsp";
    }

    //登录验证码生成
    public void createCode(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        int width = 60;
        int height = 30;
        String data = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789abcdefghijklmnpqrstuvwxyz";    //随机字符字典，其中0，o，1，I 等难辨别的字符最好不要
        Random random = new Random();//随机类
        //1 创建图片数据缓存区域（核心类）
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);//创建一个彩色的图片
        //2 获得画板(图片，ps图层)，绘画对象。
        Graphics g = image.getGraphics();
        //3 选择颜色，画矩形3，4步是画一个有内外边框的效果
        g.setColor(Color.BLACK);
        g.fillRect(0, 0, width, height);
        //4白色矩形
        g.setColor(Color.WHITE);
        g.fillRect(1, 1, width-2, height-2);
        /**1 提供缓存区域，为了存放4个随机字符，以便存入session */
        StringBuilder builder = new StringBuilder();
        //5 随机生成4个字符
        //设置字体颜色
        g.setFont(new Font("宋体", Font.BOLD&Font.ITALIC, 20));
        for(int i = 0 ; i < 4 ;i ++){
            //随机颜色
            g.setColor(new Color(random.nextInt(255),random.nextInt(255), random.nextInt(255)));
            //随机字符
            int index = random.nextInt(data.length());
            String str = data.substring(index, index + 1);
            /**2 缓存*/
            builder.append(str);
            //写入
            g.drawString(str, (width / 6) * (i + 1) , 20);
        }
        //给图中绘制噪音点，让图片不那么好辨别
        for(int j=0,n=random.nextInt(100);j<n;j++){
            g.setColor(Color.RED);
            g.fillRect(random.nextInt(width),random.nextInt(height),1,1);//随机噪音点
        }
        /**3 获得随机数据，并保存session*/
        String tempStr = builder.toString();
        req.getSession().setAttribute("code",tempStr);
        //.. 生成图片发送到浏览器 --相当于下载
        ImageIO.write(image, "jpg", resp.getOutputStream());
    }

    //用户登录
    public String login (HttpServletRequest req,HttpServletResponse resp) throws SQLException {
        //获取用户参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String code = req.getParameter("code");//验证码
        String auto = req.getParameter("auto");//自动登录
        //判断验证码是否正确
        HttpSession session = req.getSession();
        String code1 = (String) session.getAttribute("code");
        if (code1 == null || !code1.equals(code)) {
            //验证错误
            req.setAttribute("msg","验证码错误");
            return Constants.FORWARD+"/login.jsp";
        }

        //调用业务逻辑
        User user = userService.login(username, password);
        //响应
        if (user==null){
            //账号密码错误
            req.setAttribute("msg","账号或者密码错误");
            return Constants.FORWARD+"/login.jsp";
        }
        //判断是否勾选自动登录
        if (auto == null) {
            //没有勾选
            Cookie autoCookie = new Cookie("autoCookie","");
            autoCookie.setPath("/");
            autoCookie.setMaxAge(0);
            resp.addCookie(autoCookie);
        }else {
            //勾选后将信息放入cookie
            Cookie autoCookie = new Cookie("autoCookie",user.getUsername()+":"+user.getUpassword());
            autoCookie.setPath("/");
            autoCookie.setMaxAge(14*24*60*60);
            resp.addCookie(autoCookie);
        }

        //登录成功回到首页
        session.setAttribute("loginUser",user);
        return Constants.REDIRECT+"/index.jsp";
    }

    //用户注销登录
    public String logOut(HttpServletRequest req,HttpServletResponse resp){
        //去除session用户数据
        HttpSession session = req.getSession();
        session.removeAttribute("loginUser");
        //清空覆盖cookie信息
        Cookie autoCookie = new Cookie("autoCookie", "");
        autoCookie.setPath("/");
        autoCookie.setMaxAge(0);
        resp.addCookie(autoCookie);
        //转发登录页面
        req.setAttribute("msg","注销登录成功");
        return Constants.FORWARD+"/login.jsp";
    }
}
